const db = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/config');

const UserModel = {
  // 注册
  register: async (username, password, email, phone) => {
    const hashedPassword = await bcrypt.hash(password, 10);
    console.log(hashedPassword);
    console.log(username,password,phone,email);
    
    
    const [result] = await db.execute(
      'INSERT INTO users (username, password, email, phone) VALUES (?, ?, ?, ?)',
      [username, hashedPassword, email, phone]
    );
    return result.insertId;
  },
  
  // 登录
  login: async (username, password) => {
    const [rows] = await db.execute(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );
    
    if (rows.length === 0) return null;
    
    const user = rows[0];
    console.log(user);
    
    const isMatch = await bcrypt.compare(password, user.password);
    
    if (!isMatch) return null;
    
    // 生成token
    const token = jwt.sign(
      { id: user.id, username: user.username },
      JWT_SECRET,
      { expiresIn: '24h' }
    );
    
    return { ...user, token };
  },
  
  // 获取用户信息
  getUserById: async (id) => {
    const [rows] = await db.execute(
      'SELECT id, username, email, phone, avatar, created_at FROM users WHERE id = ?',
      [id]
    );
    return rows[0] || null;
  },
  
  // 更新用户信息
  updateUser: async (id, updateData) => {
    const { username, email, phone, avatar } = updateData;
    const [result] = await db.execute(
      'UPDATE users SET username = ?, email = ?, phone = ?, avatar = ? WHERE id = ?',
      [username, email, phone, avatar, id]
    );
    return result.affectedRows > 0;
  },
  
  // 更新密码
  updatePassword: async (id, oldPassword, newPassword) => {
    const [rows] = await db.execute(
      'SELECT password FROM users WHERE id = ?',
      [id]
    );
    
    if (rows.length === 0) return false;
    
    const isMatch = await bcrypt.compare(oldPassword, rows[0].password);
    if (!isMatch) return false;
    
    const hashedPassword = await bcrypt.hash(newPassword, 10);
    const [result] = await db.execute(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedPassword, id]
    );
    
    return result.affectedRows > 0;
  }
};

module.exports = UserModel;